package com.ews.onlineexchange.controller;

import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.enterprise.context.ConversationScoped;
import javax.enterprise.event.Event;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.inject.Inject;
import javax.inject.Named;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import javax.persistence.Transient;

import com.ews.onlineexchange.service.*;
import com.ews.onlineexchange.util.AesUtil;
import com.ews.onlineexchange.util.SerialnumberUtil;
import org.apache.commons.lang3.StringUtils;
import org.primefaces.event.FileUploadEvent;
import org.primefaces.event.NodeCollapseEvent;
import org.primefaces.event.NodeExpandEvent;
import org.primefaces.event.NodeSelectEvent;
import org.primefaces.event.NodeUnselectEvent;
import org.primefaces.event.SelectEvent;
import org.primefaces.event.UnselectEvent;
import org.primefaces.model.CheckboxTreeNode;
import org.primefaces.model.DefaultStreamedContent;
import org.primefaces.model.StreamedContent;
import org.primefaces.model.TreeNode;

import com.ews.onlineexchange.dao.SectorDao;
import com.ews.onlineexchange.model.AgentService;
import com.ews.onlineexchange.model.Attachment;
import com.ews.onlineexchange.model.DataEntity;
import com.ews.onlineexchange.model.Image;
import com.ews.onlineexchange.model.MainBusiness;
import com.ews.onlineexchange.model.QualificationCert;
import com.ews.onlineexchange.model.QualificationTemplate;
import com.ews.onlineexchange.model.RejectRecord;
import com.ews.onlineexchange.model.Sector;
import com.ews.onlineexchange.model.ServiceSupplier;
import com.ews.onlineexchange.model.Trade;
import com.ews.onlineexchange.model.User;
import com.ews.onlineexchange.service.qualifier.MessagePushWsEvent;
import com.ews.onlineexchange.service.qualifier.ServiceSupplierRejectEvent;
import com.ews.onlineexchange.util.AttachmentUtils;

@Named
@ConversationScoped
public class ServiceSupplierHome extends EntityHome<ServiceSupplier, String> {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	
	@Inject
	UserSeqNoGenerator userSeqNoGenerator;
	
	@Inject
	RejectRecordHome rejectRecordHome;
	
	@Inject
	SectorService sectorService;
	
	@Inject
	AttachmentUtils attachmentUtils;
	
	@Inject
	@ServiceSupplierRejectEvent
	Event<ServiceSupplier>							serviceSupplierRejectEvent;
	
	@Inject
	@MessagePushWsEvent
	Event<String>									messagePushWsEvent;
	
	@Inject
	MessgaePushService								messgaePushService;
	
	private boolean									self;
	
	private String confirmPassword;
	private Boolean alwaysValid;
	
	private MainBusiness currentBusiness;
	private String currentBusinessIndex;
	private QualificationCert currentCert;
	private String currentCertIndex;
	private QualificationTemplate currentQualificationTemplate;
	private String currentQualificationTemplateIndex; 
	
	private RejectRecord rejectRecord;
	
//	private AgentService selectedAgentService;
	private Map<String,AgentService> selectedAgentServiceMap = new LinkedHashMap<>();
	private Map<String, Map<String, TreeNode>> rootNodeMap = new LinkedHashMap<>();
	private Map<String, Map<String, TreeNode[]>> selectedNodeMap = new LinkedHashMap<>();
	
	private boolean debug;
	
	//行业部门评分
	private Integer minScore_profession = 0;
	private Integer maxScore_profession = 30;
	private String tempCreditCode;

	public String getTempCreditCode() {
		return tempCreditCode;
	}

	public void setTempCreditCode(String tempCreditCode) {
		this.tempCreditCode = tempCreditCode;
	}

	@Override
	public void initConversation() {
		super.initConversation();
		conversation.setTimeout(1000 * 60 * 20);
		List<MainBusiness> mainBusinesses = getInstance().getMainBusinesses();
		
		if(mainBusinesses.size() > 0 && StringUtils.isBlank(getCurrentBusinessIndex())) {
			setCurrentBusinessIndex(mainBusinesses.get(0).getBussinessIndex());
		}
		
		List<QualificationCert> certs = getInstance().getCerts();
		if(certs.size() > 0 && StringUtils.isBlank(getCurrentCertIndex())) {
			setCurrentCertIndex(currentCertIndex);
			List<QualificationTemplate> templates = getInstance().getCerts().get(0).getQualificationTemplates();
					if(templates.size() > 0 && StringUtils.isBlank(getCurrentQualificationTemplateIndex())) {
						setCurrentQualificationTemplateIndex(templates.get(0).getTemplateIndex());
					}
		}
	
	}

	@Override
	public ServiceSupplier createInstance() {
		ServiceSupplier instance = super.createInstance();
		String uuid = instance.addEmptyBusiness();
		setCurrentBusinessIndex(uuid);
//		instance.addEmptyCert();
		if (isDebug())
			debug(instance);
		return instance;
	}

	@Override
	public ServiceSupplier loadInstance() {
		ServiceSupplier instance = super.loadInstance();
		setTempCreditCode(instance.getCreditCode());
		return instance;
	}

	public Map<String, AgentService> getSelectedAgentServiceMap() {
		return selectedAgentServiceMap;
	}

	public void setSelectedAgentServiceMap(Map<String, AgentService> selectedAgentServiceMap) {
		this.selectedAgentServiceMap = selectedAgentServiceMap;
	}

	@Override
	public String getId() {
		if ( isSelf() ) {
			this.setId( userService.getLoginedUser().getId() );
		}
		return super.getId();
	}
	
	private void debug(ServiceSupplier instance) {
		String randomSuffix = getRandomSuffix(10000);
		instance.setCnname("山东卓智软件有限公司".concat(randomSuffix));
		instance.setCompanyType("有限公司");
//		instance.setCreditCode("913705007884532580");
//		instance.setUsername("zzrj".concat(randomSuffix));
		instance.setEmail("zzrj" + randomSuffix + "@sdews.com");
		instance.setRegisteredFund(new BigDecimal(1000000));
		instance.setRegistrationAuthority("测试机关");
		instance.setRegtime(new Date());
		instance.setAddress("东营软件园9号楼");
		instance.setLegalPerson("刘方亮");
		instance.setLegalPersonPhoneNumber("18888888888");
		instance.setFirstContactor("张志伟");
		instance.setFirstContactorPhoneNumber("16666666666");
		instance.setSecondContactor("张志伟");
		instance.setSecondContactorPhoneNumber("16666666666");
		instance.setRegion("370501");
		instance.setAlwaysValid(true);
		instance.setEmployeeCount(30);
		instance.setHighTitleEmployeeCount(10);
		instance.setMediumTitleEmployeeCount(10);
		instance.setBeginnerTitleEmployeeCount(10);
		instance.setIntro("此人太懒，没有什么可以介绍的！");
		MainBusiness business = instance.getMainBusinesses().get(0);
		business.setCommitOfPrice("test");
		business.setCommitOfQuality("test");
		business.setCommitOfTime("test");
		
	}
	
	public Integer getMinScore_profession() {
		return minScore_profession;
	}

	public void setMinScore_profession(Integer minScore_profession) {
		this.minScore_profession = minScore_profession;
	}

	public Integer getMaxScore_profession() {
		return maxScore_profession;
	}

	public void setMaxScore_profession(Integer maxScore_profession) {
		this.maxScore_profession = maxScore_profession;
	}

	private String getRandomSuffix(int multi) {
		return new Integer((int)(Math.random() * multi)).toString();
	}

	public Boolean getAlwaysValid() {
		return alwaysValid;
	}

	public void setAlwaysValid(Boolean alwaysValid) {
		this.alwaysValid = alwaysValid;
	}

	public String getConfirmPassword() {
		return confirmPassword;
	}

	public void setConfirmPassword(String confirmPassword) {
		this.confirmPassword = confirmPassword;
	}

	public MainBusiness getCurrentBusiness() {
		return currentBusiness;
	}

	public void setCurrentBusiness(MainBusiness currentBusiness) {
		this.currentBusiness = currentBusiness;
	}



	public String getCurrentBusinessIndex() {
		return currentBusinessIndex;
	}

	public void setCurrentBusinessIndex(String currentBusinessIndex) {
		this.currentBusinessIndex = currentBusinessIndex;
	}

	public QualificationCert getCurrentCert() {
		return currentCert;
	}

	public void setCurrentCert(QualificationCert currentCert) {
		this.currentCert = currentCert;
	}
	
	
	
	public String getCurrentCertIndex() {
		return currentCertIndex;
	}

	public void setCurrentCertIndex(String currentCertIndex) {
		this.currentCertIndex = currentCertIndex;
	}

	private TreeNode getRootSectorNode() {
		if (getCurrentCert() == null)
			return null;
		
		TreeNode rootNode = new CheckboxTreeNode(getSectorMap(null, "行业列表", null), null);
		Map<String, TreeNode> tnMap = new LinkedHashMap<>();
		getCurrentCert().getQualificationClass().getRootSectors().size();
		for (Sector sector : getCurrentCert().getQualificationClass().getRootSectors()) {
			List<Object[]> sectorList = sectorDao.querySectorInTree(sector.getId());
			for (Object[] objects : sectorList) {
				String id = (String) objects[0];
				String name = (String) objects[1];
				String parentId = (String) objects[2];
				
				TreeNode tn = null;
				TreeNode parentNode = tnMap.get(parentId);	
				if (parentNode != null) {
					tn = new CheckboxTreeNode(getSectorMap(id, name, parentId), parentNode);
				} else {
					tn = new CheckboxTreeNode(getSectorMap(id, name, parentId), rootNode);
					rootNode.getChildren().add(tn);
				}
				tnMap.put(id, tn);
			}
		}
		
		return rootNode;
	}
	
	private Object getSectorMap(String id, String name, String parentId) {
		Map<String, String> sectorFieldMap = new LinkedHashMap<>();
		sectorFieldMap.put("id", id);
		sectorFieldMap.put("name", name);
		sectorFieldMap.put("parentId", parentId);
		return sectorFieldMap;
	}

	public void addCurrentCertSectorId(String id) {
		Sector sector = sectorService.find(id);
		getCurrentQualificationTemplate().getSectors().add(sector);
	}

	public void onNodeExpand(NodeExpandEvent event) {
		
	}
	
	public void onNodeCollapse(NodeCollapseEvent event) {
		
	}
	
	public void onNodeSelect(NodeSelectEvent event) {
		Map<String, String> map = (Map<String, String>) event.getTreeNode().getData();
		addCurrentCertSectorId(map.get("id"));
	}
	
	public void onNodeUnselect(NodeUnselectEvent event) {
		Map<String, String> map = (Map<String, String>) event.getTreeNode().getData();		
		for (Sector sector : getCurrentQualificationTemplate().getSectors()) {
			if (sector.getId().equals(map.get("id"))) {
				getCurrentQualificationTemplate().getSectors().remove(sector);
			}
		}
	}
	
	public void uploadAttachment(FileUploadEvent event) {
		if (event.getFile() == null)
			return ;
		
		Attachment attr = attachmentUtils.getAttachmentFromUpload(event.getFile());
		getInstance().getAttachments().add(attr);
		FacesMessage message = new FacesMessage(event.getFile().getFileName() + " 上传成功。");
        FacesContext.getCurrentInstance().addMessage(null, message);
	}
	
	public void uploadCertPhotos(FileUploadEvent event) {
		if (event.getFile() == null)
			return ;
		
		com.ews.onlineexchange.model.Image attr = attachmentUtils.getImageFromUpload(event.getFile());
		attr.generateThumbnail();
		String clientId = event.getComponent().getClientId();
		String index = clientId.substring(19);
		for(QualificationCert cert : getInstance().getCerts()) {
			if(cert.getCertIndex().equals(index)) {
				cert.getCertPhotos().add(attr);
			}
		}
//		getInstance().getCerts().get(index).getCertPhotos().add(attr);
		FacesMessage message = new FacesMessage(event.getFile().getFileName() + " 上传成功。");
        FacesContext.getCurrentInstance().addMessage(null, message);
	}
	
	public void uploadAgentServicePhotos(FileUploadEvent event) {
		if (event.getFile() == null)
			return ;
		
		com.ews.onlineexchange.model.Image attr = attachmentUtils.getImageFromUpload(event.getFile());
		attr.generateThumbnail();
		String clientId = event.getComponent().getClientId();
		String str = "uploadImages";
		String index = clientId.substring( clientId.indexOf( str ) + str.length() );
		for( MainBusiness _mb : getInstance().getMainBusinesses() ) {
			if ( _mb.getBussinessIndex().equals( index ) ) {
//				business.getImages().add( attr );
				_mb.getImages().add( attr );
			}
		}

		FacesMessage message = new FacesMessage(event.getFile().getFileName() + " 上传成功。");
        FacesContext.getCurrentInstance().addMessage(null, message);
	}
	
	public void uploadBusinessLicenseImage(FileUploadEvent event) {
		if (event.getFile() == null)
			return ;
		com.ews.onlineexchange.model.Image attr = attachmentUtils.getImageFromUpload(event.getFile());
		attr.generateThumbnail();
		if(isManaged())getInstance().getBusinessLicenseImages().clear();
		getInstance().getBusinessLicenseImages().add(attr);
		FacesMessage message = new FacesMessage(event.getFile().getFileName() + " 上传成功。");
        FacesContext.getCurrentInstance().addMessage(null, message);
	}
	
	public StreamedContent getBusinessLicenseImageStreamedContent() {
		if (getInstance().getBusinessLicenseImages().size() == 0)
			return null;
		return new DefaultStreamedContent(new ByteArrayInputStream(getInstance().getBusinessLicenseImages().get(0).getThumbnailData()));
	}
	
	public void uploadTaxProveImages(FileUploadEvent event) {
		if (event.getFile() == null)
			return ;
		com.ews.onlineexchange.model.Image attr = attachmentUtils.getImageFromUpload(event.getFile());
		attr.generateThumbnail();
		getInstance().getTaxProveImages().add(attr);
		FacesMessage message = new FacesMessage(event.getFile().getFileName() + " 上传成功。");
        FacesContext.getCurrentInstance().addMessage(null, message);
	}
	
	
	
	public StreamedContent getPhotoStreamedContent(Image image) {
		if (image == null)
			return null;
		return new DefaultStreamedContent(new ByteArrayInputStream(image.getThumbnailData()));
	}
	
	@Inject
	UserService userService;
	
	@Inject
	BlackListService blackListService;
	@Inject
	ServiceSupplierService serviceSupplierService;
	@Override
	public String saveAndFlush() {
		boolean managed = isManaged();
		updateOperator(userService.getLoginedUser());
		String creditCode = getInstance().getCreditCode();
		if(!SerialnumberUtil.isRightSerialnumber(creditCode)){
			FacesContext.getCurrentInstance().addMessage("creditCode",
					new FacesMessage(FacesMessage.SEVERITY_ERROR, "统一社会信用代码格式有误，请检查！", ""));
			return null;
		}else{
			if(!creditCode.equals(tempCreditCode)){
				if(serviceSupplierService.isExistCreditCode(creditCode)){
					FacesContext.getCurrentInstance().addMessage("creditCode",
							new FacesMessage(FacesMessage.SEVERITY_ERROR, "统一社会信用代码已存在！", ""));
					return null;
				}
			}
		}
		if(getInstance().getBusinessLicenseImages().size() == 0) {
			FacesContext.getCurrentInstance().addMessage("businessLicenseImageUpload",
					new FacesMessage(FacesMessage.SEVERITY_ERROR, "营业执照需要上传图片！", ""));
			return null;
		}
		
		if(!getInstance().isAlwaysValid()) {
			if(getInstance().getBusnissAllotedTime() == null) {
				FacesContext.getCurrentInstance().addMessage("busnissAllotedTime",
						new FacesMessage(FacesMessage.SEVERITY_ERROR, "请填写营业期限!", ""));
				return null;
			}
			
		}
		
//		if(getInstance().getTaxProveImages().size() == 0) {
//			FacesContext.getCurrentInstance().addMessage("taxProveImagesUpload",
//					new FacesMessage(FacesMessage.SEVERITY_ERROR, "纳税证明需要至少上传一张图片！", ""));
//			return null;
//		}
		
		for (int i = 0;i<getInstance().getCerts().size();i++) {
			if(getInstance().getCerts().get(i).getCertPhotos().size() == 0) {
				FacesContext.getCurrentInstance().addMessage("certPhotos"+(i+1),
						new FacesMessage(FacesMessage.SEVERITY_ERROR, "资质证书"+(i+1)+"至少添加一个扫描图片！", ""));
				return null;
			}
			List<QualificationTemplate> templates = getInstance().getCerts().get(i).getQualificationTemplates();
			for (QualificationTemplate qualificationTemplate : templates) {
				if(qualificationTemplate.getSectors().size() == 0) {
					FacesContext.getCurrentInstance().addMessage("certPhotos"+(i+1),
							new FacesMessage(FacesMessage.SEVERITY_ERROR, "资质证书"+(i+1)+"需要选择行业范围！", ""));
					return null;
				}
			}
		}
		
//		if (getInstance().getAttachments().size() == 0) {
//			FacesContext.getCurrentInstance().addMessage("attachmentUploadFile",
//					new FacesMessage(FacesMessage.SEVERITY_ERROR, "请至少上传一个附件！", ""));
//			return null;
//		}
//		if (blackListService.validateUserInBlackList(getInstance().getCnname(), getInstance().getCreditCode())) {
//			FacesContext.getCurrentInstance().addMessage("",
//					new FacesMessage(FacesMessage.SEVERITY_ERROR, "你所注册的用户名称和组织机构代码/统一征信代码被列为黑名单，无法注册！", ""));
//			return null;
//		}
		if (!managed) {
			getInstance().setRoles("supplier");
			getInstance().setSeqNo(userSeqNoGenerator.getNextSeqNo());
			getInstance().setShiroPwd(userService.entryptPassword(getInstance().getPassword()));
		}
		
		for (QualificationCert cert : getInstance().getCerts()) {
			for (QualificationTemplate qt : cert.getQualificationTemplates()) {
				qt.setQualificationClass(qt.getQualificationLevel().getQualificationClass());
			}
		}
		String result = super.save();
		
		if (!managed && result.equals(RESULT_SAVED)) {
			super.flush();
			return result;
		} else if (managed && result.equals(RESULT_SAVED)) {
			super.flush();
			FacesContext.getCurrentInstance().addMessage("", new FacesMessage("修改成功。"));
			return result;
		} else {
			return null;
		}
	}
	
	
	
//	public String 
	
	public String reSubmit() {
			//当重新提交审核，重新查询一下用户，查询最新的auditted
			//由于loginedUser 只是加载一次的，故当重新提交后，重新更新一下当前登录用户，可 使审核失败的菜单隐藏
//			String username = keycloakUserService.findLoginedUsername();
			if(!getInstance().isAlwaysValid()) {
				if(getInstance().getBusnissAllotedTime() == null) {
					FacesContext.getCurrentInstance().addMessage("busnissAllotedTime",
							new FacesMessage(FacesMessage.SEVERITY_ERROR, "请填写营业期限!", ""));
					return null;
				}
				
			}
			User user = userService.findLoginedUser();
			updateOperator(userService.getLoginedUser());
			user.setAuditted(null);
			userService.setLoginedUser(user);
			getInstance().setCurrRejectRecord(null);
			getInstance().setAuditted(null);
//			getInstance().setAuditUser(null);
			return super.saveAndFlush();
		
	} 
	
	public String reSubmitAdmin() {
		updateOperator(userService.getLoginedUser());
		if(!getInstance().isAlwaysValid()) {
			if(getInstance().getBusnissAllotedTime() == null) {
				FacesContext.getCurrentInstance().addMessage("busnissAllotedTime",
						new FacesMessage(FacesMessage.SEVERITY_ERROR, "请填写营业期限!", ""));
				return null;
			}
		}
		getInstance().setCurrRejectRecord(null);
		getInstance().setAuditDate(null);
		getInstance().setAuditUser(null);
		getInstance().setAuditted(null);
		getInstance().setValid(false);
		return super.saveAndFlush();
	
} 
	
	public String reSubmitBussinessLicense() {
		updateOperator(userService.getLoginedUser());
		if ( getInstance().getBusinessLicenseImages().size() == 0 ) {
			FacesContext.getCurrentInstance().addMessage("businessLicenseImageUpload",
					new FacesMessage(FacesMessage.SEVERITY_ERROR, "营业执照需要上传图片！", ""));
			return null;
		}
		for ( MainBusiness _mb : getInstance().getMainBusinesses() ) {
			if(_mb.getAgentService() == null) {
				FacesContext.getCurrentInstance().addMessage("",
						new FacesMessage(FacesMessage.SEVERITY_ERROR, "请填写服务事项！！", ""));
			}
		}
		getInstance().setAuditted( null );
		getInstance().setCurrRejectRecord( null );
		String result = super.saveAndFlush();
		if ( result.equals( RESULT_SAVED ) ) {
			FacesContext.getCurrentInstance().addMessage( "", new FacesMessage( "修改成功。" ) );
		}
		return "unitInfo.xhtml" ;
	
} 
	
	public String audit() {
//		keycloakUserService.enableUser(getInstance());
		getInstance().setAuditDate(new Date());
		getInstance().setAuditUser(userService.getLoginedUser());
		getInstance().setAuditted(true);
		getInstance().setValid(true);
		String result = super.saveAndFlush();
		if (result.equals(RESULT_SAVED)) {
			return "auditted";
		}
		return null;
	}
	
	public String auditCerts() {
		List<QualificationCert> certs = getInstance().getCerts();
		for(QualificationCert cert:certs) {
			cert.setValid(true);
		}
		getInstance().setCerts(certs);
		String result = super.saveAndFlush();
		if (result.equals(RESULT_SAVED)) {
			return "auditted";
		}
		return null;
	}
	
	public String reject() {
		getInstance().setAuditDate(new Date());
		getInstance().setAuditUser(userService.getLoginedUser());
		getInstance().setAuditted(false);	
		getInstance().setValid(false);
		RejectRecord rejectRecord = rejectRecordHome.getInstance();
		getInstance().setCurrRejectRecord(rejectRecord);
		getInstance().getHistoryRejectRecords().add(rejectRecord);
		super.save();
		super.flush();
		serviceSupplierRejectEvent.fire(getInstance());
		
		//中介驳回消息推送
		String message = messgaePushService.addRegisterFailedMessage(getInstance());
		messagePushWsEvent.fire(message);
		
		return "rejected";		
	}
	
	@Override
	public String delete() {
		getInstance().setDelFlag(DataEntity.DEL_FLAG_DELETE);
		String result = super.saveAndFlush();
		if (result.equals(RESULT_SAVED)) {
//			keycloakUserService.disableUser(getInstance());
			return RESULT_DELETED;
		}
		return null;
	}
	
	public String realDelete() {
		String result = super.delete();
		if (result.equals(RESULT_DELETED)) {
//			keycloakUserService.deleteUser(getInstance());
			return RESULT_DELETED;
		}
		return null;
	}
	
	@Inject
	SectorDao sectorDao;
	public List<Object[]> getSectorTree(String rootId) {
		List<Object[]> sectorTree = sectorDao.querySectorInTree(rootId);		
		return sectorTree;
	}
	
	public StreamedContent getBusinessLicenseImage() {
		if(getInstance().getBusinessLicenseImages().size() == 0) return null;
		Image image = getInstance().getBusinessLicenseImages().get(0);
		if (image == null)
			return null;
		byte[] filedata = image.getFiledata();
		InputStream is = new BufferedInputStream(new ByteArrayInputStream(filedata));
		return new DefaultStreamedContent(is, "image/jpg");
	}

	public RejectRecord getRejectRecord() {
		return rejectRecord;
	}

	public void setRejectRecord(RejectRecord rejectRecord) {
		this.rejectRecord = rejectRecord;
	}
	
	public QualificationTemplate getCurrentQualificationTemplate() {
		return currentQualificationTemplate;
	}

	public void setCurrentQualificationTemplate(QualificationTemplate currentQualificationTemplate) {
		this.currentQualificationTemplate = currentQualificationTemplate;		
	}



	public String getCurrentQualificationTemplateIndex() {
		return currentQualificationTemplateIndex;
	}

	public void setCurrentQualificationTemplateIndex(String currentQualificationTemplateIndex) {
		this.currentQualificationTemplateIndex = currentQualificationTemplateIndex;
		if (this.getSelectedNodeMap().get(getCurrentCertIndex()) == null) {
			this.getSelectedNodeMap().put(getCurrentCertIndex(), new LinkedHashMap<>());
		}
	}


	
	public Map<String, Map<String, TreeNode>> getRootNodeMap() {
		return rootNodeMap;
	}

	public void setRootNodeMap(Map<String, Map<String, TreeNode>> rootNodeMap) {
		this.rootNodeMap = rootNodeMap;
	}

	public Map<String, Map<String, TreeNode[]>> getSelectedNodeMap() {
		return selectedNodeMap;
	}

	public void setSelectedNodeMap(Map<String, Map<String, TreeNode[]>> selectedNodeMap) {
		this.selectedNodeMap = selectedNodeMap;
	}

	public void initRootNode() {		
		Map<String, TreeNode> _nodeMap = null;
		if (getRootNodeMap().get(getCurrentCertIndex()) == null) {
			_nodeMap = new LinkedHashMap<String, TreeNode>();
			getRootNodeMap().put(getCurrentCertIndex(), _nodeMap);			
		} else {
			_nodeMap = getRootNodeMap().get(getCurrentCertIndex());
		}
		
		TreeNode rootNode = null;
		if (_nodeMap.get(getCurrentQualificationTemplateIndex()) == null) {
			rootNode = getRootSectorNode();
			_nodeMap.put(currentQualificationTemplateIndex, rootNode);
		}
	}
	
	
	public void changeQualificationClass() {
		getRootNodeMap().remove(getCurrentCertIndex());
		getSelectedNodeMap().remove(getCurrentCertIndex());
		if(null != getCurrentCert()) {
			List<QualificationTemplate> templates = getCurrentCert().getQualificationTemplates();
			for (QualificationTemplate qualificationTemplate : templates) {
				qualificationTemplate.getSectors().clear();
			}
		}
		
	}
	
	public void chooseSectors() {
		getCurrentQualificationTemplate().getSectors().clear();
		TreeNode[] currentTree = getSelectedNodeMap().get(getCurrentCertIndex()).get(getCurrentQualificationTemplateIndex());
		for (TreeNode treeNode : currentTree) {
			if (treeNode.getChildCount() > 0)
				continue;
			String id = ((HashMap<String, String>)treeNode.getData()).get("id");
			addCurrentCertSectorId(id);
		}
	}
		
	public void removeQualificationTemplate(String cert_index,String qt_index) {
		if (getSelectedNodeMap() != null) {
			Map<String, TreeNode[]> map = getSelectedNodeMap().get(getCurrentCertIndex());
			if (map != null)
				map.remove(getCurrentQualificationTemplateIndex());	
		}
		QualificationTemplate removeTemplate = null;
		for(QualificationTemplate template:getCurrentCert().getQualificationTemplates()) {
			if(getCurrentQualificationTemplateIndex().equals(template.getTemplateIndex()) ) {
				removeTemplate = template;
			}
		}
		if(removeTemplate != null) {
			getCurrentCert().getQualificationTemplates().remove(removeTemplate);
		}
//		getCurrentCert().removeQualificationTemplate(getCurrentQualificationTemplateIndex());
	}
	
	public void removeBusiness() {
		String bussinessIndex = getCurrentBusinessIndex();
		List<MainBusiness> mainBusinesses = getInstance().getMainBusinesses();
		for (MainBusiness _mb : mainBusinesses) {
			if(_mb.getBussinessIndex().equals(bussinessIndex)) {
				mainBusinesses.remove(_mb);
			}
		}
		this.setCurrentBusinessIndex("");
		this.setCurrentBusiness(null);
		if(selectedAgentServiceMap.get(bussinessIndex) != null) {
			selectedAgentServiceMap.remove(bussinessIndex);
		}
	}
	
	public void removeCert() {
		List<QualificationCert> certs = getInstance().getCerts();
		QualificationCert removeCert = null;
		for(QualificationCert cert : certs) {
			if(getCurrentCertIndex() == cert.getCertIndex()) {
				removeCert = cert;
			}
		}
		if(removeCert != null) {
			certs.remove(removeCert);
		}
		this.setCurrentCert(null);
		this.setCurrentCertIndex("");
		this.setCurrentQualificationTemplate(null);
		this.setCurrentQualificationTemplateIndex("");
	}
	
	@Inject
	EntityManager entityManager;
	private String GET_RATED_TRADE_LIST = ""
			+" SELECT trade  "
			+" FROM Trade trade "
			+" LEFT JOIN Bulletin bulletin "
			+" ON trade.bulletin.id = bulletin.id"
			+" WHERE  bulletin.done = true "
			+" AND bulletin.applyDone = true "
			+" AND trade.supplier.id = :supplierId ";
	@Transient
	public List<Trade> getRatedTradeList(){
		Query query = entityManager.createQuery(GET_RATED_TRADE_LIST);
		query.setParameter("supplierId", getInstance().getId());
		return query.getResultList();
	}

	public boolean isDebug() {
		return debug;
	}

	public void setDebug(boolean debug) {
		this.debug = debug;
	}
	
	public void removeCertPhoto(int certIndex, Image photo) {	
		this.getInstance().getCerts().get(certIndex).getCertPhotos().remove(photo);
	}
	
	public void removeAgentServicePhoto(int agentServiceIndex, Image photo) {	
//		this.getInstance().getBusinesses().get(agentServiceIndex).getImages().remove(photo);
		getInstance().getMainBusinesses().get(agentServiceIndex).getImages().remove(photo);
	}
	
	public void removeTaxImage( Image taxImage) {
		this.getInstance().getTaxProveImages().remove(taxImage);
	}
	
	public void removeAttachment(Attachment attachment) {
		getInstance().getAttachments().remove(attachment);
	}
	
	public void  removeBussinessImage() {
		getInstance().getBusinessLicenseImages().remove(0);
	}
	
	public void onRowSelect(SelectEvent event) {
		AgentService service = (AgentService) event.getObject();
    } 
	
    public void onRowUnselect(UnselectEvent event) {
        
    }
    
    public void updateAgentService() {
    	getCurrentBusiness().setAgentService(selectedAgentServiceMap.get(currentBusinessIndex));
    }
    
    @Transient
	public String getAgentServiceName() {
		
		return getCurrentBusiness().getAgentService().getName();
	}
    
    public boolean checkAgentService(AgentService agentSerice) {
    	boolean checked = false;
    	List<MainBusiness> mainBusinesses = getInstance().getMainBusinesses();
    	for (MainBusiness _mb : mainBusinesses) {
			AgentService service = _mb.getAgentService();
			if(service != null) {
				if(agentSerice.getId() .equals(service.getId())) {
					checked = true;
					break;
				}
			}else {
				continue;
			}
		}
    	return checked;
    }
    
    private List<QualificationTemplate> templates = new ArrayList<>();
    public boolean checkQualificationTemplate(QualificationTemplate qualificationTemplate) {
    	boolean checked = false;
    	List<QualificationCert> certs = getInstance().getValidCerts();
    	if(templates.size() == 0) {
    		for (QualificationCert qualificationCert : certs) {
    			templates.addAll((qualificationCert.getQualificationTemplates()));
			}
    	}
    	for (QualificationTemplate template : templates) {
			if(template != null) {
				if(template.getQualificationClass().getId() .equals(qualificationTemplate.getQualificationClass().getId()) && template.getQualificationLevel().getValue() <= qualificationTemplate.getQualificationLevel().getValue()) {
					checked = true;
					break;
				}
			}else {
				continue;
			}
		}
    	return checked;
    }
    
    public QualificationTemplate getSameQualificationTemplate(QualificationTemplate qualificationTemplate) {
    	List<QualificationCert> certs = getInstance().getCerts();
    	QualificationTemplate validTemplate = null;
    	QualificationTemplate invalidTemplate = null;
    	if(templates.size() == 0) {
    		for (QualificationCert qualificationCert : certs) {
    			
    			List<QualificationTemplate> qualificationTemplates = qualificationCert.getQualificationTemplates();
    			for (QualificationTemplate qualificationTemplate2 : qualificationTemplates) {
    				qualificationTemplate2.setCertAuditedResult(qualificationCert.getAuditResult());
    				templates.add(qualificationTemplate2);
				}
			}
    	}
    	
    	for (QualificationTemplate template : templates) {
			if(template != null) {
				if(template.getQualificationClass().getId() .equals(qualificationTemplate.getQualificationClass().getId())) {
					if(template.getCertAuditedResult() != null && template.getCertAuditedResult()) {
						validTemplate = template;
					}else {
						invalidTemplate = template;
					}
				}
			}
			if(null != validTemplate) {
				return validTemplate;
			}
		}
    	
    	return invalidTemplate;
    	
    }
    
    private List<Sector> sectors = new ArrayList<>();
    
    public Sector getSameSector(Sector sector) {
    	List<QualificationCert> certs = getInstance().getCerts();
    	Sector validSector = null;
    	Sector invalidSector = null;
    	if(sectors.size() == 0) {
    		for (QualificationCert qualificationCert : certs) {
    			
    			List<QualificationTemplate> qualificationTemplates = qualificationCert.getQualificationTemplates();
    			for (QualificationTemplate qualificationTemplate2 : qualificationTemplates) {
    				List<Sector> templatesSectors = qualificationTemplate2.getSectors();
    				for (Sector sector2 : templatesSectors) {
						sector2.setCertAuditedResult(qualificationCert.getAuditResult());
						sectors.add(sector2);
					}
				}
			}
    	}
    	
    	for (Sector mySector : sectors) {
			if(mySector != null) {
				if(mySector.getId() .equals(sector.getId())) {
					if(mySector.getCertAuditedResult()) {
						validSector = mySector;;
					}else {
						invalidSector = mySector;
					}
				}
			}
			if(null != validSector) {
				return validSector;
			}
		}
    	return invalidSector;
    }

	public boolean isSelf() {
		return self;
	}

	public void setSelf( boolean self ) {
		this.self = self;
	}
}
